﻿namespace BorgExt
{
    public class Extension : MetaElement
    {
        internal bool reflectionHandlersAdded;
        internal object extensionObject;

        internal CompositionEventHandler<ExtensionEventArgs>[] ActivatedEventHandlers { get; set; }
        internal CompositionEventHandler<ExtensionEventArgs>[] DeactivatedEventHandlers { get; set; }

        public ExtensionType ExtensionType { get; private set; }

        public MetaElementCollection<Plug> Plugs { get; internal set; }
        public MetaElementCollection<Slot> Slots { get; internal set; }

        public object Object
        {
            get { return Composer.GetExtensionObject(this); }
        }

        public bool IsActivated
        {
            get { return InstanceStore.IsActivated(this); }
        }

        public bool IsShared
        {
            get { return InstanceStore.IsShared(this); }
        }

        public event CompositionEventHandler<ExtensionEventArgs> Activated
        {
            add
            {
                lock (LockObject)
                    ActivatedEventHandlers = ArrayEx.Add(ActivatedEventHandlers, value);
            }
            remove
            {
                lock (LockObject)
                    ActivatedEventHandlers = ArrayEx.Remove(ActivatedEventHandlers, value);
            }
        }

        public event CompositionEventHandler<ExtensionEventArgs> Deactivated
        {
            add
            {
                lock (LockObject)
                    DeactivatedEventHandlers = ArrayEx.Add(DeactivatedEventHandlers, value);
            }
            remove
            {
                lock (LockObject)
                    DeactivatedEventHandlers = ArrayEx.Remove(DeactivatedEventHandlers, value);
            }
        }

        internal Extension(int id, ExtensionType extensionType)
            : base(id, extensionType.Name)
        {
            ExtensionType = extensionType;
        }

        public object Activate()
        {
            return Composer.Activate(this);
        }

        public void Deactivate()
        {
            Composer.Deactivate(this);
        }

        public void Destroy()
        {
            Composer.Destroy(this);
        }

        internal override AssemblyElement GetAssemblyElement()
        {
            return ExtensionType.Plugin;
        }
    }
}

